package com.app.micaihu.view.set;

import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.app.micaihu.R;
import com.app.micaihu.app.AppApplication;
import com.app.micaihu.base.BaseOldActivity;
import com.app.micaihu.configure.AppConfigTools;
import com.app.micaihu.configure.Config;
import com.app.micaihu.configure.ConfigKeyConstant;
import com.app.micaihu.configure.URIContant;
import com.app.micaihu.configure.UserConfigTools;
import com.app.micaihu.custom.view.SwitchButton;
import com.app.micaihu.db.UserDBDAO;
import com.app.micaihu.db.UserSQLiteOpenHelper;
import com.app.micaihu.manager.AppConfigManager;
import com.app.micaihu.manager.IPushManager;
import com.app.micaihu.manager.UserInforManager;
import com.app.utils.ChannelUtil;
import com.app.micaihu.utils.CheckVersionUtils;
import com.app.micaihu.utils.DialogUtils;
import com.app.micaihu.utils.InteractiveUtils;
import com.app.utils.NetUtils;
import com.app.micaihu.view.user.userinfo.activity.WebActivity;
import com.app.utils.biz.Biz;
import com.app.utils.util.AppTools;
import com.app.utils.util.ToastUtils;
import com.app.utils.util.ViewSizeUtils;
import com.app.utils.util.file.AppFileUtils;
import com.app.utils.util.image.LoadImageUtils;
import com.baidu.mobstat.StatService;
import com.jeremyliao.liveeventbus.LiveEventBus;
import com.jeremyliao.liveeventbus.core.LiveEvent;

import java.io.File;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.HashMap;

/**
 * 设置页面
 *
 * @author linkai
 * Created by linkai on 2016/8/4.
 */
public class SetActivity extends BaseOldActivity implements OnClickListener, DialogUtils.OnDialogBtnClickListener {


    private SwitchButton mWifiView;// 仅wifi查看图片
    private TextView mTextSizeView;// 字体大小
    private TextView mVersionSize;// 当前版本号
    private TextView mCacheSzieView;// 缓存大小
    private SwitchButton mPullView;// 是否推送
    private View mAboutView;// 关于
    private View mFontSizeView;// 字体设置
    private View mPingfenView;// 评分
    private View mVersionView;// 版本更新
    private View mClearCacheView;// 清理缓存
    private View mYijianView;// 帮助与反馈

    //逻辑数据
    private AlertDialog mfontDialog;//设置字体弹窗


    // 页面数据变量
    private String[] sizes = new String[]{AppApplication.getInstance().getString(R.string.set_textsize_xiao)
            , AppApplication.getInstance().getString(R.string.set_textsize_zhong)
            , AppApplication.getInstance().getString(R.string.set_textsize_da)
            , AppApplication.getInstance().getString(R.string.set_textsize_teda)
            , AppApplication.getInstance().getString(R.string.set_textsize_chaoda)};// 字号
    private SharedPreferences mSharePreferences;
    private View mCancelLogin;
    private View mBlacklist;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addContentView(R.layout.activity_set);
        initView();
        initdata();// 初始化页面数据
    }


    @Override
    protected void onStart() {
        super.onStart();
        if (mCancelLogin != null) {
            mCancelLogin.setVisibility(UserInforManager.getInstance().isLogin() ? View.VISIBLE : View.GONE);
        }
    }

    /**
     * 初始化view
     */
    private void initView() {
        setTitle("设置");
        findViewById(R.id.page_head_title).setOnClickListener(this);
        mWifiView = (SwitchButton) findViewById(R.id.option_wifi);
        mTextSizeView = (TextView) findViewById(R.id.textView_size);
        mCacheSzieView = (TextView) findViewById(R.id.clear);
        mVersionSize = (TextView) findViewById(R.id.option_version_size);
        mPullView = (SwitchButton) findViewById(R.id.option_pull);
        mAboutView = findViewById(R.id.option_about);
        mFontSizeView = findViewById(R.id.option_textsize);
        mPingfenView = findViewById(R.id.option_pingfen);
        mVersionView = findViewById(R.id.option_vertion);
        mClearCacheView = findViewById(R.id.option_clear);
        mYijianView = findViewById(R.id.option_yijian);

        mCancelLogin = findViewById(R.id.textView_cancel_login);


        mBlacklist = findViewById(R.id.option_blacklist);

        mAboutView.setOnClickListener(this);
        mFontSizeView.setOnClickListener(this);
        mPingfenView.setOnClickListener(this);
        mPullView.setOnClickListener(this);
        mWifiView.setOnClickListener(this);
        mVersionView.setOnClickListener(this);
        mClearCacheView.setOnClickListener(this);
        mYijianView.setOnClickListener(this);
        mCancelLogin.setOnClickListener(this);
        mBlacklist.setOnClickListener(this);
    }

    /**
     * 初始化数据
     */
    private void initdata() {
        mSharePreferences = AppConfigManager.getInstance().getConfigSP();
        // 设置字体大小
        mTextSizeView.setText(sizes[mSharePreferences.getInt(ConfigKeyConstant.option_textSize, 1)]);
        // 设置是否仅WiFi加载图片
        mWifiView.setChecked(mSharePreferences.getBoolean(ConfigKeyConstant.option_isWifi, false));
        // 加载缓存大小
        new Thread() {
            @Override
            public void run() {
                double cacheSize = 0;
                try {
                    cacheSize = AppFileUtils.getFolderSize(new File(AppConfigTools.SDCARDPATH1));
                    cacheSize += AppFileUtils.getFolderSize(new File(AppConfigTools.SDCARDPATH));
                } catch (Exception e) {
                    e.printStackTrace();
                }
                //Double值取得小数点后两位方法
                final double cacheSize2 = new BigDecimal((cacheSize) / 1024 / 1024 / 2).setScale(2, RoundingMode.UP).doubleValue();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mCacheSzieView.setText(cacheSize2 + "MB");
                    }
                });

            }
        }.start();

        // 设置版本号
        mVersionSize.setText(AppTools.getVersionName());
        // 设置文章推送通知
        mPullView.setChecked(mSharePreferences.getBoolean(ConfigKeyConstant.option_isPull, true));
    }


    /**
     * 设置字体dialog
     */
    public void setFont() {
        if (mfontDialog == null) {
            View view = getLayoutInflater().inflate(
                    R.layout.dialog_set_textsize, null);
            View parent = view.findViewById(android.R.id.background);
            parent.getLayoutParams().width = ViewSizeUtils.getWidthPixels() / 5 * 4;
//            View mCancel = view.findViewById(android.R.id.text1);
//            View mConfrim = view.findViewById(android.R.id.text2);
            TextView mCancel = (TextView) view.findViewById(R.id.btn_negative);
            TextView mConfrim = (TextView) view.findViewById(R.id.btn_positive);
            mCancel.setText(getResources().getString(R.string.common_cancel));
            mConfrim.setText(getResources().getString(R.string.common_confirm));
            final RadioGroup mRadioGroup = (RadioGroup) view
                    .findViewById(R.id.text_radio_group);
            switch (UserConfigTools.textSize) {
                case 0:
                    mRadioGroup.check(android.R.id.button1);
                    break;
                case 1:
                    mRadioGroup.check(android.R.id.button2);
                    break;
                case 2:
                    mRadioGroup.check(android.R.id.button3);
                    break;
                case 3:
                    mRadioGroup.check(R.id.button4);
                    break;
                case 4:
                    mRadioGroup.check(R.id.button5);
                    break;
                default:
                    mRadioGroup.check(android.R.id.button1);
                    break;
            }

            OnClickListener onclick = new OnClickListener() {

                @Override
                public void onClick(View view) {
                    switch (view.getId()) {
                        case R.id.btn_negative:// 退出
                            if (mfontDialog != null) {
                                try {
                                    mfontDialog.dismiss();
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                            break;
                        case R.id.btn_positive:// 确定
                            int mTextSize;
                            int radCheck = mRadioGroup.getCheckedRadioButtonId();
                            switch (radCheck) {
                                case android.R.id.button1:
                                    mTextSize = 0;
                                    break;
                                case android.R.id.button2:
                                    mTextSize = 1;
                                    break;
                                case android.R.id.button3:
                                    mTextSize = 2;
                                    break;
                                case R.id.button4:
                                    mTextSize = 3;
                                    break;
                                case R.id.button5:
                                    mTextSize = 4;
                                    break;
                                default:
                                    mTextSize = 0;
                                    break;
                            }
                            Editor ed = mSharePreferences.edit();
                            ed.putInt(ConfigKeyConstant.option_textSize, mTextSize);
                            ed.commit();
                            UserConfigTools.textSize = mTextSize;
                            mTextSizeView.setText(sizes[UserConfigTools.textSize]);
                            break;
                        default:
                            break;
                    }
                    //取消dialog
                    if (mfontDialog != null) {
                        try {
                            mfontDialog.dismiss();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
            };
            mCancel.setOnClickListener(onclick);
            mConfrim.setOnClickListener(onclick);
            if (!isFinishing()) {
                mfontDialog = new AlertDialog.Builder(this, R.style.Dialog).create();
                mfontDialog.show();
                mfontDialog.setCanceledOnTouchOutside(true);
                mfontDialog.getWindow().setContentView(view);
                mfontDialog.getWindow().setGravity(Gravity.CENTER);
            }
        } else {
            try {
                if (!isFinishing()) {
                    mfontDialog.show();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }


    }


    // 文章推送 wifi加载图片 显示列表摘要 提示版本更新
    private void setSwitchButton(SwitchButton view, String key) {
        Editor ed = mSharePreferences.edit();
        ed.putBoolean(key, view.isChecked());
        ed.commit();


    }

    // 清空缓存
    private void cleatCache() {
        if ("0.0MB".equals(mCacheSzieView.getText())) {
            ToastUtils.makeText(AppApplication.getInstance().getString(R.string.set_clear_cache_no));
            return;
        }

        HashMap<String, String> style = new HashMap<>();
        style.put("title", mActivity.getResources().getString(R.string.common_prompt));
        style.put("desc", this.getString(R.string.set_clear_cache_sure));
        style.put("btnPosi", this.getString(R.string.common_confirm));
        style.put("btnNega", this.getString(R.string.common_cancel));

        DialogUtils.getInstance().setOnDialogBtnClick(this);
        DialogUtils.getInstance().showCustomDialog(this, style);

    }

    /* 评分 */
    private void pingfeng() {
        Uri uri = Uri.parse("market://details?id=" + getPackageName());
        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
        try {
            startActivity(intent);
        } catch (ActivityNotFoundException e) {
            ToastUtils.showText(AppApplication.getInstance().getString(R.string.set_nomark));
        }
    }


    /**
     * 所有事件
     */
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.textView_cancel_login://注销
                if (UserInforManager.getInstance().isLogin()) {
                    UserInforManager.getInstance().setUserInfor(null);
                    Biz.getInstance().setUserInfo("");
                    Biz.getInstance().setUserTask("");
                    LiveEventBus.get(Config.EventBus.logOutSuccess).post(true);
                    InteractiveUtils.getInstance().readLaudFromLocal();
                    onBackPressed();
                    StatService.onEvent(this, "053", "注销", 1);// 统计的点击
                }
                break;
            case R.id.option_textsize:
                // 设置字体
                setFont();
                StatService.onEvent(this, "053", "设置字体", 1);// 统计的点击
                break;
            case R.id.option_pull:
                setSwitchButton(mPullView, ConfigKeyConstant.option_isPull);// 推送通知
                if (mPullView.isChecked()) {
                    IPushManager.getInstance().startPush();
                    StatService.onEvent(this, "053", "打开推送", 1);// 统计的点击
                } else {
                    IPushManager.getInstance().endPush();
                    StatService.onEvent(this, "053", "关闭推送", 1);// 统计的点击
                }
                break;
            case R.id.option_wifi://是否仅wifi加载
                setUserWifi();
                StatService.onEvent(this, "053", "仅wifi查看图片", 1);// 统计的点击
                break;
            case R.id.option_clear:
                cleatCache();// 清理缓存
                StatService.onEvent(this, "053", "清理缓存", 1);// 统计的点击
                break;
            case R.id.option_vertion://检测升级
                new CheckVersionUtils().checkVertion(this, true);
                StatService.onEvent(this, "053", "检测升级", 1);// 统计的点击
                break;
            case R.id.option_about:// 关于我们
                Intent intent = new Intent(this, WebActivity.class);
                intent.putExtra("title", "关于我们");
                intent.putExtra("url", URIContant.ABOUT_WE);
                startActivity(intent);
                StatService.onEvent(this, "053", "关于我们", 1);// 统计的点击
                break;
            case R.id.option_pingfen://评分
                pingfeng();
                StatService.onEvent(this, "053", "评分", 1);// 统计的点击
                break;
            case R.id.option_yijian:// 意见反馈
                startActivity(new Intent(this, AliFeedBackActivity.class));
                StatService.onEvent(this, "053", "反馈", 1);// 统计的点击
                break;
            case R.id.page_head_title://头部设置点击
                showChannel();
                break;
            case R.id.option_blacklist:
                if (UserInforManager.getInstance().isLogin()) {
                    startActivity(new Intent(this, BlacklistActivity.class));

                } else {
                    UserInforManager.getInstance().toLoginPage(this);
                }
                break;


        }
    }

    private void clearCachOnThread() {
        final Handler handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                mCacheSzieView.setText("0.0MB");
                ToastUtils.makeText(getString(R.string.set_clear_cache_suces));
            }
        };
        new Thread() {
            public void run() {
                AppFileUtils.clearCache(new File(AppConfigTools.SDCARDPATH1));// 清除所有缓存图片
                AppFileUtils.clearCache(new File(AppConfigTools.SDCARDPATH));// 清除所有缓存图片
                handler.sendEmptyMessage(0);
            }

            ;
        }.start();
    }

    /**
     * 设置当前网络是否加载
     */
    private void setUserWifi() {
        if (mWifiView == null) {
            return;
        }
        setSwitchButton(mWifiView, ConfigKeyConstant.option_isWifi);// 仅wifi加载图片
        UserConfigTools.isUseWifi = mWifiView.isChecked();
        int netType = NetUtils.getNetworkType();//获取当前网络类型
        if (netType == NetUtils.NETTYPE_CM && UserConfigTools.isUseWifi) {
            //当前网络为移动网络并且开启了仅wifi加载图片  不允许加载图片
            LoadImageUtils.getInstance().setIsLoadImg(false);
            AppConfigTools.isLoadImage = false;
        } else {
            LoadImageUtils.getInstance().setIsLoadImg(true);
            AppConfigTools.isLoadImage = true;
        }
    }

    /**
     * 弹出当前的渠道
     */
    int coiniuClick;//总点击次数

    private void showChannel() {
        coiniuClick++;
        //如果点击超过5次则统计，用于版本后台统计测试
        if (coiniuClick >= 5) {
            StatService.onEvent(this, "012", "渠道点击", 1);
            String channel = ChannelUtil.getChannel(this, "no_channel");
            String device = AppTools.getIMEI();
            ToastUtils.showText("当前渠道:\n" + channel + "\n" + device);
            coiniuClick = 0;//重置为0，重新统计
        }
    }


    @Override
    public void onPositiveClick() {
        DialogUtils.getInstance().dismissCustomDialog();
        clearCachOnThread();
    }

    @Override
    public void onNegativeClick() {
        DialogUtils.getInstance().dismissCustomDialog();
    }
}


